package com.pig4cloud.pigx.common.customize.websocket.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pig4cloud.pigx.common.customize.utils.CommonUtil;
import com.pig4cloud.pigx.common.security.service.PigxUser;
import com.pig4cloud.pigx.common.websocket.distribute.MessageDO;
import com.pig4cloud.pigx.common.websocket.distribute.RedisMessageDistributor;
import com.pig4cloud.pigx.common.websocket.holder.SessionKeyGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.Collections;
import java.util.Objects;

/**
 * @date 2022/8/25 16:40
 */
@Slf4j
@Component
@AllArgsConstructor
public class WebSocketUtils {

	/**
	 * pigx框架sessionKey获取器
	 */
	private final SessionKeyGenerator sessionKeyGenerator;
	/**
	 * pigx框架消息发布器
	 */
	private final RedisMessageDistributor messageDistributor;
	private final ObjectMapper objectMapper;
	private final CommonUtil commonUtil;

	/**
	 * 发送消息给指定客户端
	 *
	 * @param session 客户端session
	 * @param data    发送的数据
	 * @date 2022/8/26 18:55
	 */
	public void sendMsg(WebSocketSession session, Object data) {
		MessageDO messageDO = new MessageDO();
		messageDO.setMessageText(commonUtil.toJson(data));
		messageDO.setSessionKeys(Collections.singletonList(sessionKeyGenerator.sessionKey(session)));
		messageDO.setNeedBroadcast(false);
		messageDistributor.distribute(messageDO);
	}

	/**
	 * 发送消息给指定客户端
	 *
	 * @param sessionKey 客户端sessionKey
	 * @param data       发送的数据
	 * @date 2022/8/26 18:55
	 */
	public void sendMsg(Object sessionKey, Object data) {
		MessageDO messageDO = new MessageDO();
		messageDO.setMessageText(commonUtil.toJson(data));
		messageDO.setSessionKeys(Collections.singletonList(sessionKey));
		messageDO.setNeedBroadcast(false);
		messageDistributor.distribute(messageDO);
	}

	/**
	 * 获得当前用户的id作为sessionMap的key
	 *
	 * @param session websocket会话
	 * @return {@link Long}
	 * @date 2022/8/25 17:31
	 */
	public Long getSessionKey(WebSocketSession session) {
		try {
			OAuth2Authentication authentication = (OAuth2Authentication) session.getPrincipal();
			PigxUser user = (PigxUser) authentication.getPrincipal();
			if (Objects.isNull(user.getId())) {
				throw new RuntimeException();
			}

			return user.getId();
		} catch (Throwable e) {
			e.printStackTrace();
			throw new RuntimeException("未能获取用户信息");
		}
	}
}
